<template>
  <div ref="gantt"></div>
</template>

<script>
import 'dhtmlx-gantt'

export default {
  name: 'gantt',
  props: {
    tasks: {
      type: Object,
      default() {
        return {data: [], links: []}
      }
    }
  },
  methods: {
    $_initGanttEvents: function () {
      if (!gantt.$_eventsInitialized) {
        gantt.attachEvent('onTaskSelected', (id) => {
          let task = gantt.getTask(id);
          this.$emit('task-selected', task);
        });

        gantt.attachEvent('onTaskIdChange', (id, new_id) => {
          if (gantt.getSelectedId() === new_id) {
            let task = gantt.getTask(new_id);
            this.$emit('task-selected', task);
          }
        });

        gantt.$_eventsInitialized = true;
      }
    },

    $_initDataProcessor: function () {
      if (!gantt.$_dataProcessorInitialized) {
        gantt.createDataProcessor((entity, action, data, id) => {
          this.$emit(`${entity}-updated`, id, action, data);
        });

        gantt.$_dataProcessorInitialized = true;
      }
    }
  },

  mounted: function () {
    this.$_initGanttEvents();

    gantt.locale = {
      // 汉化
      date: {
        month_full: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
        month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
        day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
        day_short: ["日", "一", "二", "三", "四", "五", "六"]
      },
      labels: {
        dhx_cal_today_button: "今天",
        day_tab: "日",
        week_tab: "周",
        month_tab: "月",
        new_event: "新建日程",
        icon_save: "保存",
        icon_cancel: "关闭",
        icon_details: "详细",
        icon_edit: "编辑",
        icon_delete: "删除",
        confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
        confirm_deleting: "是否删除计划?",
        section_description: "任务内容:",
        section_time: "时间范围:",
        section_type: "类型",
        section_text: "任务名称:",
        section_color: "颜色:",

        /* grid columns */

        column_text: "项目节点名称",
        column_start_date: "开始时间",
        column_duration: "持续时间",
        column_add: "",

        /* link confirmation */

        link: "关联",
        confirm_link_deleting: "将被删除",
        link_start: " (开始)",
        link_end: " (结束)",

        type_task: "任务",
        type_project: "项目",
        type_milestone: "里程碑",

        minutes: "分钟",
        hours: "小时",
        days: "天",
        weeks: "周",
        months: "月",
        years: "年"
      }
    };
    // 甘特图数据日期格式化
    gantt.config.xml_date = "%Y-%m-%d";
    gantt.config.scale_unit = 'year'
    gantt.config.date_scale = "1";		//设置时间刻度的格式（X轴） 多个尺度
    gantt.config.scale_height = 50; //设置时间刻度的高度和网格的标题
    gantt.config.duration_unit = 'day' // minute, day, month
    // 在时间线上增加一行年份显示
    gantt.config.subscales = [
      {unit: "month", step: 1, date: "%M"}
    ];
    // 只读模式
    gantt.config.readonly = false

    //左侧是否自适应
    gantt.config.autofit = false;
    //左侧宽
    gantt.config.grid_width = 350;
    //取消连线
    gantt.config.drag_links = false;
    //只读
    gantt.config.readonly = true;
    //右侧显示列名
    gantt.config.date_scale = "%Y-%m-%d";
    //自动调整图表坐标轴区间用于适配task的长度
    gantt.config.fit_tasks = true;
    //弹窗宽
    gantt.config.wide_form = false;

    gantt.init(this.$refs.gantt);
    gantt.parse(this.$props.tasks);

    //弹出层
    gantt.config.lightbox.sections = [
      {name: "text", height: 70, map_to: "text", type: "textarea", focus: true, width: 200},
      {name: "time", height: 30, map_to: "auto", type: "time", time_format: ["%Y", "%m", "%d"]},
      {
        name: "color", height: 30, map_to: "color", type: "select", options: [
          {key: "#3db9d3", label: "蓝色"},
          {key: "#33cc33", label: "绿色"},
          {key: "#FF8247", label: "橙色"},
          {key: "#ff6633", label: "红色"}
        ]
      },
      {name: "description", height: 70, map_to: "description", type: "textarea"}
    ];
    //左侧显示列名
    gantt.config.columns = [
      {name: "text", label: "任务名称", tree: true, width: '*'},
      {name: "start_date", label: "开始时间", align: "center", width: 100},
      {name: "end_date", label: "结束时间", align: "center", width: 100},
    ];
    // 隐藏添加按钮
    gantt.templates.grid_row_class = function (start, end, task) {
      return "nested_task"
    };
    let dragging_task = 0;
    gantt.attachEvent("onAfterTaskDrag", function(id, mode, e){
      let modes = gantt.config.drag_mode;
      if(mode === modes.move){
        if (dragging_task && id === dragging_task){
          let target_index = Math.floor(y_pos / gantt.config.row_height);

          let target_task = gantt.getTaskByIndex(target_index - 1);
          if (!target_task) target_task = gantt.getTaskByIndex(gantt.getVisibleTaskCount() - 1);

          if (target_task.type !== 'project') {
            let copy_object = gantt.copy(target_task);
            gantt.changeTaskId(target_task.id,+new Date())
            gantt.addTask(copy_object, target_task.id)
            target_task.type = 'project';
            target_task.render = ['split'];
          }

          let task = gantt.getTask(id);
          if (task.parent) {
            let original_parent = gantt.getTask(task.parent);
            let children = gantt.getChildren(task.parent)
            //if (children.length == 1) original_parent.type = gantt.config.types.task;
          }
          task.parent = target_task.id;

          gantt.updateTask(target_task.id)
          gantt.updateTask(id)
          gantt.render()
        }
        dragging_task = 0;
        gantt.refreshTask(id)
      }
    });


    this.$_initDataProcessor();
  }
}
</script>

<style>
@import "~dhtmlx-gantt/codebase/dhtmlxgantt.css";

.gantt_add, .gantt_grid_head_add {
  display: none !important;
}
</style>